import Vue from "vue";
import Router from "vue-router";
import userRouter from "./modules/user";
import businessRouter from "./modules/business";
import informationRouter from "./modules/information";
import merchantRouter from "./modules/merchant";
import adminRouter from "./modules/admin";

import Container from "@/container";
import store from "@/store";

Vue.use(Router);
// 公共路由
export const constRoutes = [
  {
    path: "/",
    component: Container,
    children: [
      {
        path: "/",
        component: () => import("@/pages/layout")
      }
    ]
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/pages/login")
  }
];
// 权限路由
export const varRoutes = [
  {
    path: "/",
    name: "layout",
    component: () => import("@/pages/layout"),
    children: [
      businessRouter,
      informationRouter,
      userRouter,
      merchantRouter,
      adminRouter
    ]
  },
  {
    path: "*",
    redirect: "/"
  }
];

const createRouter = () =>
  new Router({
    mode: "history",
    routes: constRoutes
  });

const router = createRouter();

export const resetRouter = () => {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
};

router.beforeEach(async (to, from, next) => {
  if (to.name === "login") {
    next();
  } else {
    const hasToken = sessionStorage.getItem("Token");
    if (hasToken) {
      if (to.path === "/login") {
        next({ path: "/" });
      } else {
        const hasPermitIds =
          store.getters.routes && store.getters.routes.length > 0;
        if (hasPermitIds) {
          next();
        } else {
          const permitIds = await store.dispatch("user/getPermitIds");
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            permitIds
          );
          store.dispatch(
            "user/getLoginUserInfo",
            sessionStorage.getItem("userId")
          );

          router.addRoutes(accessRoutes);
          console.log("permitIds-reset!!!!!!!!!!!!!!!!");
          next({ ...to, replace: true });
        }
      }
    } else {
      next("/login");
    }
  }
});

export default router;
